package org.jivesoftware.spark.component;

import org.jivesoftware.spark.util.log.Log;

import javax.swing.JEditorPane;
import javax.swing.JPanel;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.html.HTMLEditorKit;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

public class HTMLViewer extends JPanel
{
	private JEditorPane browser;
	
	public HTMLViewer()
	{
		final JPanel mainPanel = new JPanel();
		browser = new JEditorPane();
		browser.setEditorKit(new HTMLEditorKit());
		
		setLayout(new GridBagLayout());
		
		this.add(mainPanel, new GridBagConstraints(0, 2, 1, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstriants.BOTH, new Insets(0, 0, 0, 0), 0, 0));
	}
	
	public void setHTMLContent(String text)
	{
		browser.setText(text);
	}
	
	public void loadURL(String url)
	{
		try
		{
			if (url.startsWith("www"))
			{
				url = "http://" + url;
			}
			browser.setPage(url);
		}
		catch(Exception ex)
		{
			Log.error(ex);
		}
	}
	
	public String getSelectedText()
	{
		return browser.getSelectedText();
	}
	
	public Dimension getPreferredSize()
	{
		final Dimension size = super.getPreferredSize();
		size.width = 0;
		return size;
	}
	
	public void setHyperlinkListener(HyperlinkListener listener)
	{
		browser.addHyperlinkListener(listener);
	}
}
